#ifndef SOCKET_H_
#define SOCKET_H_

#include<winsock.h>
#include<string.h>
#include<stdio.h>
#pragma comment(lib, "ws2_32.lib")
class fwq
{
	WSADATA wsaData;      
    SOCKET sListen;      
    SOCKET sClient;      
    SOCKADDR_IN local;      
    SOCKADDR_IN client;      
    char szMessage[1024];      
    int ret;      
    int iaddrSize = sizeof(SOCKADDR_IN);
    public:
    	explicit fwq(bool print=false)
    	{
    		WSAStartup(0x0202, &wsaData);
		    sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		    local.sin_family = AF_INET;
		    local.sin_port = htons(5150);
		    local.sin_addr.s_addr = htonl(INADDR_ANY);
		    bind(sListen, (struct sockaddr *) &local, sizeof(SOCKADDR_IN));
		    ::listen(sListen, 1);
		    sClient = accept(sListen, (struct sockaddr *) &client, &iaddrSize);
		    if(print) printf("Accepted client:%s:%d\n", inet_ntoa(client.sin_addr),ntohs(client.sin_port));
		}
		~fwq(){}
		const char* listen()
		{
			ret = recv(sClient, szMessage, 1024, 0);
	        szMessage[ret] = '\0';
	        return szMessage;
		}
		void Return(const char* msg)
		{
			::send(sClient, msg, strlen(msg), 0);
		}
};
class khd
{
	WSADATA wsaData;
    SOCKET sClient;
    SOCKADDR_IN server;
    char szMessage[1024];
    int ret;
    public:
    	khd(const char *ip)
    	{
    		WSAStartup(0x0202, &wsaData);
		    sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		    memset(&server, 0, sizeof(SOCKADDR_IN));
		    server.sin_family = PF_INET;
		    server.sin_port = htons(5150);
		    server.sin_addr.s_addr = inet_addr(ip);
		    connect(sClient, (struct sockaddr *) &server, sizeof(SOCKADDR_IN));
		}
		~khd()
		{
			closesocket(sClient);
    		WSACleanup();
		}
		void send(char *msg,char* (*func)(char*))
		{
			if(msg==NULL)
			{
		        func(szMessage);
		        ::send(sClient, szMessage, strlen(szMessage), 0);
			}
			else
			{
				::send(sClient, msg, strlen(msg), 0);
			}
			
		}
		void Receive(char* szBuffer)
		{
			int len=recv(sClient, szBuffer, 1024, 0);
			szBuffer[len]='\0';
		}
};

#endif